package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.entity.Income;
import com.sunday.scoremanager.entity.RecordDetail;
import com.sunday.scoremanager.http.ApiClient;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/26.
 */

public class HyProfitActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    ImageView btnBack;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.my_total_score)
    TextView myTotalScore;
    @Bind(R.id.txt)
    TextView txt;
    @Bind(R.id.total_score)
    TextView totalScore;
    @Bind(R.id.relase_score)
    TextView relaseScore;
    @Bind(R.id.my_profit)
    TextView myProfit;
    @Bind(R.id.btn_withdraw)
    TextView btnWithdraw;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;


    private long memberId;
    private List<RecordDetail> dataSet = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private CommonAdapter<RecordDetail> adapter;
    private boolean isCanloadMore;
    private int lastVisibleItem;
    private int pageNo = 1;
    private String selectDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hy_profit);
        ButterKnife.bind(this);
        initView();
        getData();
    }

    private void initView(){
        memberId = BaseApp.getInstance().getMember().getSellerId();
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<RecordDetail>(mContext, R.layout.list_income_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, RecordDetail recordDetail) {
                bind(holder, recordDetail);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }
    private void bind(ViewHolder holder, RecordDetail recordDetail) {
        TextView score = holder.getView(R.id.profit);
        TextView time = holder.getView(R.id.time);
        TextView from = holder.getView(R.id.from);
        score.setText(recordDetail.getAmount().setScale(2, RoundingMode.HALF_UP)+"");
        time.setText(recordDetail.getTime());
        from.setText(recordDetail.getMemo());

    }
    private Income income;
    private void getData() {
        Call<ResultDO<Income>> call = ApiClient.getApiAdapter().myAssets(memberId,2, 2);
        call.enqueue(new Callback<ResultDO<Income>>() {
            @Override
            public void onResponse(Call<ResultDO<Income>> call, Response<ResultDO<Income>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    income = response.body().getResult();
                    updateView();
                    getRecordDetail();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Income>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void updateView() {
        if (income == null) {
            return;
        }
        myTotalScore.setText(income.getHuaiYaScore().setScale(2, RoundingMode.HALF_UP) + "");
        myProfit.setText(income.getHuaiYaMoney().setScale(2, RoundingMode.HALF_UP) + "");
        totalScore.setText(income.getTotalHuaiYaScore().setScale(2, RoundingMode.HALF_UP) + "");
        relaseScore.setText(income.getReleaseHuaiYaCore().setScale(2, RoundingMode.HALF_UP) + "");
    }

    private void getRecordDetail() {
        Call<ResultDO<List<RecordDetail>>> call = ApiClient.getApiAdapter().recordDetail(memberId,2, 2, pageNo, Constants.PAGE_SIZE, selectDate);
        call.enqueue(new Callback<ResultDO<List<RecordDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<RecordDetail>>> call, Response<ResultDO<List<RecordDetail>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult() != null && response.body().getResult().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<RecordDetail>>> call, Throwable t) {

            }
        });
    }


    @OnClick(R.id.btn_withdraw)
    void withDraw() {
        intent = new Intent(mContext, WithDrawScoreProfitActivity.class);
        startActivity(intent);
    }
}
